﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Ext.Net;
using Ext.Net.Utilities;
using MemberMgr.Data.BusinessObjects;
using MemberMgr.Data.ManagerObjects;
using System.Data;

namespace MemberMgr.Website.Admin
{
    public partial class UserAdmin : Common.TabPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                ItShopManager shopMgr = Common.CommonUtil.managerFactory.GettShopManager();
                ItRoleManager roleMgr = Common.CommonUtil.managerFactory.GettRoleManager();

                IList<tShop> shoplist = shopMgr.GetAll();
                IList<tRole> rolelist = roleMgr.GetAll();

                this.cmbShopSearch.Items.Clear();
                this.cmbShopID.Items.Clear();
                this.cmbRoleID.Items.Clear();

                foreach (tShop item in shoplist)
                {
                    this.cmbShopSearch.Items.Add(new Ext.Net.ListItem(item.Shopname, item.Id.ToString()));
                    this.cmbShopID.Items.Add(new Ext.Net.ListItem(item.Shopname, item.Id.ToString()));
                }

                foreach (tRole item in rolelist)
                {
                    this.cmbRoleID.Items.Add(new Ext.Net.ListItem(item.Rolename, item.Id.ToString()));
                }

            }
        }

        protected void RowSelect(object sender, DirectEventArgs e)
        {
            uint userID = uint.Parse(e.ExtraParams["userID"]);

            ItUserManager userMgr = Common.CommonUtil.managerFactory.GettUserManager();

            tUser user = userMgr.GetById(userID);

            if (user != null)
            {
                this.fpUserDetail.SetValues(new
                {
                    user.Id,
                    user.Userid,
                    user.Username,
                    user.Email,
                    Shopid = user.TShop.Id,
                    Roleid = user.TRole.Id
                });
            }
        }

        protected void storeUserList_Refresh(object sender, StoreRefreshDataEventArgs e)
        {
            this.storeUserList.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindDataSource();
        }

        private void BindDataSource()
        {
            string userName = this.txtSearchName.Text;
            string shopID = this.cmbShopSearch.SelectedItem.Value;

            ItUserManager userMgr = Common.CommonUtil.managerFactory.GettUserManager();
            IList<tUser> list = null;

            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(shopID))
            {
                list = userMgr.GetUserInfoByNameAndShopID(userName, uint.Parse(shopID));
            }
            else if (!string.IsNullOrEmpty(userName))
            {
                list = userMgr.GetUserInfoByName(userName);
            }
            else if (!string.IsNullOrEmpty(shopID))
            {
                list = userMgr.GetBySHOPID(uint.Parse(shopID));
            }
            else
            {
                list = userMgr.GetAll();
            }

            if (list != null)
            {
                DataTable dt = this.GetMemberInfoDataTable();

                foreach (tUser item in list)
                {
                    dt.Rows.Add(
                        item.Id,
                        item.Userid,
                        item.Username,
                        item.Email,
                        item.TShop.Id,
                        item.TRole.Id,
                        item.TShop.Shopname,
                        item.TRole.Rolename
                        );
                }

                this.storeUserList.DataSource = dt;
                this.storeUserList.DataBind();
            }
        }

        private DataTable GetMemberInfoDataTable()
        {
            DataTable dt = new DataTable();

            dt.Columns.AddRange(new DataColumn[] { 
                new DataColumn() { ColumnName="ID",DataType=typeof(uint)},
                new DataColumn() { ColumnName="USERID",DataType=typeof(string)},
                new DataColumn() { ColumnName="USERNAME",DataType=typeof(string)},
                new DataColumn() { ColumnName="EMAIL",DataType=typeof(string)},
                new DataColumn() { ColumnName="SHOPID",DataType=typeof(int)},
                new DataColumn() { ColumnName="ROLEID",DataType=typeof(int)},
                new DataColumn() { ColumnName="SHOPNAME",DataType=typeof(string)},
                new DataColumn() { ColumnName="ROLENAME",DataType=typeof(string)}
            });

            return dt;
        }

        [DirectMethod]
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.txtID.Text.Trim()))
                {
                    Ext.Net.MessageBox errMsg = new Ext.Net.MessageBox();

                    errMsg.Show(new MessageBoxConfig()
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.INFO,
                        Title = "提示",
                        Message = "请先选择用户后再删除!"
                    });

                    return;
                }

                ItUserManager userMgr = Common.CommonUtil.managerFactory.GettUserManager();

                tUser user = userMgr.GetById(uint.Parse(this.txtID.Text.Trim()));

                if (user != null)
                {
                    userMgr.Delete(user);

                    this.BindDataSource();
                }

            }
            catch (Exception ex)
            {
                Ext.Net.MessageBox errMsg = new Ext.Net.MessageBox();

                errMsg.Show(new MessageBoxConfig()
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.ERROR,
                    Title = "数据保存失败",
                    Message = ex.Message
                });
            }
        }

        [DirectMethod]
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string id = this.txtID.Text.Trim();
            string userID = this.txtUserID.Text.Trim();
            string userName = this.txtUserName.Text.Trim();
            string email = this.txtUserEmail.Text.Trim();
            string shopid = this.cmbShopID.SelectedItem.Value;
            string roleid = this.cmbRoleID.SelectedItem.Value;
            string password1 = this.txtPassword1.Text.Trim();
            string password2 = this.txtPassword2.Text.Trim();

            //Check Data
            if (!string.IsNullOrEmpty(password1) || !string.IsNullOrEmpty(password2))
            {
                if (password1 != password2)
                {
                    Ext.Net.MessageBox errMsg = new Ext.Net.MessageBox();

                    errMsg.Show(new MessageBoxConfig()
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.INFO,
                        Title = "提示",
                        Message = "两次密码不一致，请确认!"
                    });

                    return;
                }
            }

            ItUserManager userMgr = Common.CommonUtil.managerFactory.GettUserManager();

            userMgr.Session.BeginTransaction();

            try
            {
                if (string.IsNullOrEmpty(id))
                {
                    //Add

                    //Check Data
                    if(string.IsNullOrEmpty(password1) || string.IsNullOrEmpty(password2))
                    {
                       
                            Ext.Net.MessageBox errMsg = new Ext.Net.MessageBox();

                            errMsg.Show(new MessageBoxConfig()
                            {
                                Buttons = MessageBox.Button.OK,
                                Icon = MessageBox.Icon.INFO,
                                Title = "提示",
                                Message = "新登录用户必须输入密码!"
                            });

                            return;
                    }

                    if (string.IsNullOrEmpty(password1))
                    {
                        Ext.Net.MessageBox errMsg = new Ext.Net.MessageBox();

                        errMsg.Show(new MessageBoxConfig()
                        {
                            Buttons = MessageBox.Button.OK,
                            Icon = MessageBox.Icon.INFO,
                            Title = "提示",
                            Message = "新增用户，请输入登录密码！"
                        });

                        return;
                    }

                    tUser user = new tUser();

                    user.Userid = userID;
                    user.Username = userName;
                    user.Email = email;
                    user.Password = string.IsNullOrEmpty(password1) ? user.Password : password1.Trim();

                    ItShopManager shopMgr = Common.CommonUtil.managerFactory.GettShopManager();
                    ItRoleManager roleMgr = Common.CommonUtil.managerFactory.GettRoleManager();

                    tShop shop = shopMgr.GetById(uint.Parse(shopid));

                    user.TShop = shop;

                    tRole role = roleMgr.GetById(uint.Parse(roleid));

                    user.TRole = role;

                    userMgr.Save(user);

                    userMgr.Session.CommitTransaction();
                }
                else
                {
                    //Update

                    tUser user = userMgr.GetById(uint.Parse(id));

                    if (user != null)
                    {
                        user.Userid = userID;
                        user.Username = userName;
                        user.Password = string.IsNullOrEmpty(password1) ? user.Password : password1.Trim();
                        user.Email = email;

                        ItShopManager shopMgr = Common.CommonUtil.managerFactory.GettShopManager();
                        ItRoleManager roleMgr = Common.CommonUtil.managerFactory.GettRoleManager();

                        tShop shop = shopMgr.GetById(uint.Parse(shopid));
                        tRole role = roleMgr.GetById(uint.Parse(roleid));

                        user.TShop = shop;
                        user.TRole = role;

                        userMgr.Update(user);

                        userMgr.Session.CommitTransaction();
                    }
                }

                this.BindDataSource();
            }
            catch (Exception ex)
            {
                userMgr.Session.RollbackTransaction();
                Ext.Net.MessageBox errMsg = new Ext.Net.MessageBox();

                errMsg.Show(new MessageBoxConfig()
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.ERROR,
                    Title = "数据保存失败",
                    Message = ex.Message
                });
            }

        }
    }
}
